セッターとゲッター (set, get)

您所在的位置:网站首页 javascript get set セッターとゲッター (set, get)

セッターとゲッター (set, get)

2024-07-11 12:16| 来源: 网络整理| 查看: 265

セッターとゲッター (set, get)

プロパティへのインターセプター(参照・代入・監視などの意味)としGetter/Setterがあります。

記述方法のサンプルは次のようになります。

tsclass Human { private _name: string;  public constructor(name: string) { this._name = name; }  // Getter宣言 get name(): string { return this._name; }  // Setter宣言 set name(name: string) { this._name = name; }} const human = new Human("");// Setterを利用human.name = `田中太郎`;// Getterを利用console.log(human.name);田中太郎tsclass Human { private _name: string;  public constructor(name: string) { this._name = name; }  // Getter宣言 get name(): string { return this._name; }  // Setter宣言 set name(name: string) { this._name = name; }} const human = new Human("");// Setterを利用human.name = `田中太郎`;// Getterを利用console.log(human.name);田中太郎

メソッドと違い、getter/setterを呼ぶ場合は()は不要です。

ts// Getterconsole.log(human.name); // 正しいGetterの使用方法console.log(human.name()); // エラー :human.name is not a functionThis expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'? Type 'String' has no call signatures.6234This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'? Type 'String' has no call signatures."田中太郎" // Setterhuman.name = "田中太郎"; // 正しいSetterの使用方法human.name("田中太郎");This expression is not callable. Type 'String' has no call signatures.2349This expression is not callable. Type 'String' has no call signatures.ts// Getterconsole.log(human.name); // 正しいGetterの使用方法console.log(human.name()); // エラー :human.name is not a functionThis expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'? Type 'String' has no call signatures.6234This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'? Type 'String' has no call signatures."田中太郎" // Setterhuman.name = "田中太郎"; // 正しいSetterの使用方法human.name("田中太郎");This expression is not callable. Type 'String' has no call signatures.2349This expression is not callable. Type 'String' has no call signatures.Getter​

Getterの記述方法を日本語で表すと次のようになります。

tsget 名前(): 型 { 必要ならば処理(); return 戻り値;}tsget 名前(): 型 { 必要ならば処理(); return 戻り値;}

Getterに引数を指定することはできません。また戻り値を必ず指定する必要があります。

Setter​

Setterの記述方法を日本語で表すと次のようになります。

tsset 名前(変数 : 型) { 必要ならば処理(); 保存処理();}tsset 名前(変数 : 型) { 必要ならば処理(); 保存処理();}

引数が必ずひとつ必要です。また戻り値を指定することはできません。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3